package com.yyb.controller;

import com.yyb.common.Result;
import com.yyb.constants.CoreConstant;
import com.yyb.domain.SysLoginInfo;
import com.yyb.domain.SysUser;
import com.yyb.dto.LoginUserDTO;
import com.yyb.enums.ResultEnums;
import com.yyb.enums.StateEnums;
import com.yyb.service.SysUserService;
import com.yyb.sync.AsyncSysLoginLogInfoService;
import com.yyb.utils.HttpUtils;
import com.yyb.utils.ServletUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 
 * 
 * 
 */
@RestController
@Tag(name = "用户登录接口")
public class LoginController extends BaseController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private AsyncSysLoginLogInfoService asyncSysLoginLogInfoService;


    /**
     * 用户登陆
     * POST http://127.0.0.1:8080/login
     * 接口ID：148742187
     * 接口地址：https://app.apifox.com/link/project/4040316/apis/api-148742187
     */
    @Operation(summary = "用户登录")
    @PostMapping(CoreConstant.LOGIN_URL)
    public Result login(@Validated LoginUserDTO loginUserDTO) {
        SysLoginInfo loginInfo=new SysLoginInfo();
        loginInfo.setLoginTime(new Date());
        HttpServletRequest request = ServletUtils.getRequest();
        loginInfo.setBrowser(HttpUtils.getBrowserName(request)+","+HttpUtils.getBrowserVersion(request));
        loginInfo.setUserName(loginUserDTO.getUsername());
        loginInfo.setOs(HttpUtils.getOsName(request));
        loginInfo.setIpAddr(HttpUtils.getIpAddr(request));
        try {
            //得到正确的验证码
            Object realCode = ServletUtils.getSession().getAttribute(CoreConstant.CAPTCHA_KEY);
            Assert.notNull(realCode, "验证码未生成");
            if (!realCode.toString().equalsIgnoreCase(loginUserDTO.getCode())) {
                loginInfo.setStatus(StateEnums.LOGIN_ERROR.getCode());
                loginInfo.setMsg("验证码不正确");
                return new Result(ResultEnums.ERROR, "验证码不正确");
            }
            //得到用户名和密码
            String username = loginUserDTO.getUsername();
            String password = loginUserDTO.getPassword();
            //把明文使用MD5加密
            password = DigestUtils.md5DigestAsHex(password.getBytes());
            SysUser sysUser = this.sysUserService.login(username, password);
            if (ObjectUtils.isEmpty(sysUser)) {
                loginInfo.setStatus(StateEnums.LOGIN_ERROR.getCode());
                loginInfo.setMsg(ResultEnums.USER_PASSWORD_ERROR.getMsg());
                return new Result(ResultEnums.USER_PASSWORD_ERROR);
            }
            //把用户正确的用户对象放到session里面
            sysUser.setPassword(null);
            ServletUtils.getSession().setAttribute(CoreConstant.SESSION_KEY, sysUser);
            loginInfo.setStatus(StateEnums.LOGIN_SUCCESS.getCode());
            loginInfo.setMsg(StateEnums.LOGIN_SUCCESS.getMsg());
        }finally {
            //记录日志[同步。还是异步]
            asyncSysLoginLogInfoService.saveLoginInfo(loginInfo);
        }
        //登录成功
        return new Result(ResultEnums.SUCCESS);
    }

    /**
     * 得到用户信息
     * GET http://127.0.0.1:8080/getUserInfo
     * 接口ID：148742188
     * 接口地址：https://app.apifox.com/link/project/4040316/apis/api-148742188
     */
    @Operation(summary = "得到用户信息")
    @GetMapping("getUserInfo")
    public Result<?> getUserInfo() {
        SysUser sysUser = (SysUser) ServletUtils.getSession().getAttribute(CoreConstant.SESSION_KEY);
        Assert.notNull(sysUser, "当前用户没有登录");
        Long userId = sysUser.getUserId();
        //根据ID查询用户数据
        SysUser user = this.sysUserService.queryUserById(userId);
        Assert.notNull(user, "用户不存在");
        user.setPassword(null);
        ServletUtils.getSession().setAttribute(CoreConstant.SESSION_KEY, sysUser);
        //判断用户类型 如果是超级管理管理，就查询所有权限。如果不是，就根据用户ID查询用户的权限
        Integer userType = user.getUserType();
        List<String> permissions=null;
        if(userType.equals(StateEnums.USER_TYPE_ADMIN.getCode())){
            //说明是超级管理员
            permissions=this.sysUserService.queryAllPermissions();
        }else{
            //普通用户
            permissions=this.sysUserService.queryPermissionsByUserId(user.getUserId());
        }
        //组装数据
        Map<String,Object> data=new HashMap<>();
        user.setPassword(null);
        data.put("user",user);
        data.put("permissions",permissions);
        //把当前用户的权限保存到session
        ServletUtils.getSession().setAttribute(CoreConstant.PERMISSIONS_KEY,permissions);
        return new Result<>(data);
    }

    /**
     * 退出系统
     *   GET http://127.0.0.1:8080/logout
     *   接口ID：148742189
     *   接口地址：https://app.apifox.com/link/project/4040316/apis/api-148742189
     */
    @Operation(summary = "退出系统")
    @GetMapping("logout")
    public Result logout(){
        ServletUtils.getSession().invalidate();
        return new Result(ResultEnums.SUCCESS);
    }
}
